package com.vinobase.controller.administration;


import com.vinobase.controller.management.CountryForm;
import com.vinobase.model.bean.CountryLocal;
import com.vinobase.model.bean.Region;
import com.vinobase.model.dao.CountryDao;
import com.vinobase.model.dao.RegionDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.Principal;
import java.util.Locale;
import java.util.SortedSet;

@Controller
public class RegionController {

    @Autowired
    private CountryDao countryDao;

    @Autowired
    private RegionDao regionDao;

    @ModelAttribute("countries")
    public SortedSet<CountryForm> populateCountries(Principal user, Locale locale) {
        return countryDao.getList(user, locale);
        //return null;
    }

    @RequestMapping(value="/administration/region/create.html", method=RequestMethod.GET)
    protected String getCreateForm(Model model){
        model.addAttribute(new Region());
        return "administration/region/create";
    }

    @RequestMapping(value="/administration/region/list.html")
    protected String getList(Model model) {
        model.addAttribute("regions", regionDao.getList(""));
        return "administration/region/list";
    }

    @RequestMapping(value="administration/region/create.html", method=RequestMethod.POST)
    protected String create(@Valid Region region, BindingResult result, Model model){
        if (result.hasErrors()) {
                    return "administration/region/create";
        }
        regionDao.create(region);
        return getList(model);
    }

    @RequestMapping(value="administration/region/{id}.html", method=RequestMethod.GET)
    protected String view(@PathVariable Long id, Model model){
        model.addAttribute(regionDao.get(id));
        return "administration/region/create";
    }

    @RequestMapping(value="administration/region/delete.html", method=RequestMethod.GET)
    protected String delete(HttpServletRequest request, Model model){
        regionDao.delete(Long.parseLong(request.getParameter("id")));
        return getList(model);
    }
}
